package com.chat.business.config;

import com.chat.common.json.JacksonObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //LocalDateTime时间序列化
        JacksonObjectMapper jacksonObjectMapper = new JacksonObjectMapper();
        // 创建一个自定义配置的序列化工具(json)
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(jacksonObjectMapper);

        //设置key序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());

        // 设置 value 和 hash 的序列化工具
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        template.setConnectionFactory(factory);
        return template;
    }
    @Bean(name = "redisTemplateString")
    public RedisTemplate<String, Object> redisTemplateString(RedisConnectionFactory redisConnectionFactory) {
        //创建RedisTemplate对象
        RedisTemplate<String, Object> stringObjectRedisTemplate =
                new RedisTemplate<String,Object>();
        //设置连接工厂
        stringObjectRedisTemplate.setConnectionFactory(redisConnectionFactory);
        //创建Json序列化工具
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        //设置key的序列化工具
        stringObjectRedisTemplate.setKeySerializer(RedisSerializer.string());
        //设置Value的序列化
        stringObjectRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 设置hash key的序列化器
        stringObjectRedisTemplate.setHashKeySerializer(stringRedisSerializer);
        // 设置hash value的序列化器
        stringObjectRedisTemplate.setHashValueSerializer(stringRedisSerializer);

        // 必须调用这个方法，初始化RedisTemplate
        stringObjectRedisTemplate.afterPropertiesSet();

        //返回
        return stringObjectRedisTemplate;
    }
    @Bean
    public HashOperations<String, String, Object> redisHashTemplate(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }
}